package com.bay1ts.security;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

public class DatebasePasswordSecurityUpdater extends JdbcDaoSupport {
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private SaltSource saltSource;
	@Autowired
	@Qualifier("customjdbcUserService")
	private JdbcUserDetailsManager jdbcUserDetailsManager;
	

	public void secureDatabase() {
		getJdbcTemplate().query("select username, password from users", new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);
				UserDetails user=jdbcUserDetailsManager.loadUserByUsername(username);
				String encodedPassword=passwordEncoder.encodePassword(password, saltSource.getSalt(user));
				//不加盐时的做法
				//String encodedPassword = passwordEncoder.encodePassword(password, null);
				getJdbcTemplate().update("update users set password = ? where username = ?", encodedPassword, username);
			}
		});
	}
	
}
